﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Text;
using System.Transactions;
using System.IO;

using DataDesign.MPP.Utilities;
using log4net;
namespace DataDesign.MPP.Domain
{
    public partial class DBContext : System.Data.Linq.DataContext
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static readonly string connectionString = Common.GetConnectionString();
       
        public DBContext()
            : base(connectionString)
        {

        }

        public DBContext(string connection)
            : base(connection)
        {

        }
        public System.Data.Common.DbTransaction UseTransaction()
        {
            this.Connection.Open();
            this.CommandTimeout = 3600;

            System.Data.Common.DbTransaction tran = this.Connection.BeginTransaction();
            this.Transaction = tran;

            return tran;
        }
        #region Methods
        public void Delete<T>(T item) where T : class,ICommonFunctions<T>
        {
            try
            {
                Table<T> table = this.GetTable<T>();
                item = item.GetByPrimaryKey();
                table.Attach(item as T);
                table.DeleteOnSubmit(item as T);
                this.SubmitChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }


        public void Insert<T>(T item) where T : class
        {
            try
            {
                Table<T> table = this.GetTable<T>();

                table.InsertOnSubmit(item as T);
                this.SubmitChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public void InsertAll<T>(List<T> list) where T : class
        {
            try
            {
                if (list != null)
                {
                    Table<T> table = this.GetTable<T>();

                    table.InsertAllOnSubmit(list);
                    this.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }


        public void Update<T>(T item) where T : class,ICommonFunctions<T>
        {
            try
            {
                
                T t = item.GetByPrimaryKey();
                GenericUltil.ShallowCopy<T>(item, t);

                this.GetTable<T>().Attach(t as T, true);
                this.SubmitChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
